<template>
  <n-modal
    :show="props.visible"
    preset="card"
    title="重置密码"
    style="width: 500px"
    @after-enter="handleOpen"
    @close="handleClose"
  >
    <n-form ref="formRef" :model="form" :rules="rules">
      <n-form-item :label="`请输入${data?.userName}的新密码`" path="password">
        <n-input v-model:value="form.password" placeholder="请输入新密码" clearable />
      </n-form-item>
    </n-form>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">取消</n-button>
        <n-button type="primary" @click="submitCallback" :loading="loading" :disabled="loading">
          确定
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { resetPassword } from '@/apis/system/user';
import { useMessage, type FormInst } from 'naive-ui';
import { computed, reactive, ref, useTemplateRef } from 'vue';

const props = defineProps<{ visible: boolean; data: any }>();
const emits = defineEmits(['close']);
const message = useMessage();
const loading = ref(false);
const data = computed(() => props.data);
const formRef = useTemplateRef<FormInst>('formRef');
const form = reactive({
  userId: null,
  password: null,
});
const rules = ref({
  password: [
    { required: true, message: '用户密码不能为空', trigger: 'blur' },
    {
      min: 5,
      max: 20,
      message: '用户密码长度必须介于 5 和 20 之间',
      trigger: 'blur',
    },
  ],
});

const handleOpen = async () => {
  form.userId = data.value.userId;
};

const handleClose = (needRefresh = false) => {
  emits('close', { needRefresh });
};

const submitCallback = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (errors) {
      return;
    }
    loading.value = true;
    const res: any = await resetPassword(form);
    if (res.code === 200) {
      message.success('重置密码成功');
      handleClose(true);
    }
    loading.value = false;
  });
};
</script>

<style lang="less" scoped></style>
